<template>
  <div class="page-box">
    <universal-table
      :columns="columns"
      :fetch-data="fetchTableData"
      permission-prefix="nfc:fission"
      :show-selection="true"
      :show-index="true"
      :export-file-name="'NFC裂变活动'"
      :init-search-form="{}"
      :showKeywordSearch="false"
      :showDateRange="false"
      @view="handleView"
      @delete="handleDelete"
      @reset="reset"
      ref="table">

      <!-- 搜索区域扩展 -->
      <template #searchExtend>
        <el-form-item prop="share_code">
          <el-input v-model="searchForm.share_code" placeholder="分享码" clearable style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item prop="user_openid">
          <el-input v-model="searchForm.user_openid" placeholder="用户OpenID" clearable style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item prop="merchant_id">
          <el-select v-model="searchForm.merchant_id" placeholder="选择商户" clearable style="width: 150px;">
            <el-option v-for="item in merchantOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" placeholder="裂变状态" clearable style="width: 120px;">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="template_id">
          <el-select v-model="searchForm.template_id" placeholder="选择模板" clearable style="width: 150px;">
            <el-option v-for="item in templateOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="invite_count_range">
          <div style="display: inline-flex; align-items: center; width: 280px;">
            <el-input-number
              v-model="searchForm.min_invite_count"
              placeholder="最小邀请数"
              :min="0"
              :max="999"
              controls-position="right"
              style="width: 135px;">
            </el-input-number>
            <span style="margin: 0 10px;">-</span>
            <el-input-number
              v-model="searchForm.max_invite_count"
              placeholder="最大邀请数"
              :min="0"
              :max="999"
              controls-position="right"
              style="width: 135px;">
            </el-input-number>
          </div>
        </el-form-item>
        <el-form-item prop="expire_status">
          <el-select v-model="searchForm.expire_status" placeholder="过期状态" clearable style="width: 120px;">
            <el-option label="未过期" value="active"></el-option>
            <el-option label="已过期" value="expired"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="expire_date_range">
          <el-date-picker
            v-model="searchForm.expire_date_range"
            type="daterange"
            range-separator="至"
            start-placeholder="过期开始日期"
            end-placeholder="过期结束日期"
            @change="handleExpireDateRangeChange"
            style="width: 280px;">
          </el-date-picker>
        </el-form-item>
      </template>

      <!-- 搜索区域按钮扩展 -->
      <template #searchExtend2>
        <el-form-item>
          <el-button type="primary" @click="handleAnalytics">
            <i class="el-icon-data-analysis"></i> 数据分析
          </el-button>
          <el-button type="info" @click="handleConfig">
            <i class="el-icon-setting"></i> 配置管理
          </el-button>
        </el-form-item>
      </template>

      <!-- 操作栏扩展 -->
      <template #operationExtend="{ row }">
        <el-button size="mini" type="primary" @click="handleViewInvites(row)">邀请记录</el-button>
        <el-button size="mini" type="success" @click="handleCopyShareLink(row)">复制分享</el-button>
        <el-button size="mini" type="warning" @click="handleDisable(row)" v-if="row.status === 'active'">禁用</el-button>
      </template>
    </universal-table>

    <!-- 裂变详情弹窗 -->
    <el-dialog title="裂变详情" :visible.sync="detailDialogVisible" width="800px">
      <div class="fission-detail" v-if="currentFission">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="裂变ID">{{ currentFission.id }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentFission.user_id }}</el-descriptions-item>
          <el-descriptions-item label="模板ID">{{ currentFission.template_id }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentFission.status)">{{ getStatusText(currentFission.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="分享码">{{ currentFission.share_code }}</el-descriptions-item>
          <el-descriptions-item label="邀请总数">{{ currentFission.invite_count }}</el-descriptions-item>
          <el-descriptions-item label="成功邀请">{{ currentFission.success_count }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentFission.created_at }}</el-descriptions-item>
        </el-descriptions>

        <!-- 分享链接 -->
        <div class="share-link-section" style="margin-top: 20px;">
          <h4>分享链接</h4>
          <el-input v-model="shareLink" readonly>
            <el-button slot="append" @click="copyShareLink">复制</el-button>
          </el-input>
        </div>

        <!-- 邀请统计 -->
        <div class="invite-stats" style="margin-top: 20px;">
          <h4>邀请统计</h4>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ currentFission.invite_count }}</div>
                <div class="stat-label">总邀请数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ currentFission.success_count }}</div>
                <div class="stat-label">成功邀请</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ currentFission.view_count || 0 }}</div>
                <div class="stat-label">访问次数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ getConversionRate() }}%</div>
                <div class="stat-label">转化率</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>

    <!-- 邀请记录弹窗 -->
    <el-dialog title="邀请记录" :visible.sync="inviteDialogVisible" width="900px">
      <el-table :data="inviteList" border>
        <el-table-column prop="invited_user_id" label="被邀请用户ID" width="120"></el-table-column>
        <el-table-column prop="invite_time" label="邀请时间" width="180"></el-table-column>
        <el-table-column prop="claim_time" label="领取时间" width="180">
          <template slot-scope="scope">
            {{ scope.row.claim_time || '未领取' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'claimed' ? 'success' : 'warning'">
              {{ scope.row.status === 'claimed' ? '已领取' : '未领取' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="coupon_info" label="优惠券信息">
          <template slot-scope="scope">
            {{ scope.row.coupon_info || '暂无' }}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleInviteSizeChange"
        @current-change="handleInviteCurrentChange"
        :current-page="invitePage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="invitePageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="inviteTotal"
        style="margin-top: 20px; text-align: center;">
      </el-pagination>
    </el-dialog>

    <!-- 数据分析弹窗 -->
    <el-dialog :title="getAnalyticsTitle()" :visible.sync="analyticsDialogVisible" width="1000px">
      <div class="analytics-content" v-loading="analyticsLoading" element-loading-text="正在加载数据..."
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)">

        <!-- 过滤条件显示 -->
        <div class="filter-info" v-if="analyticsData.queryParams && Object.keys(analyticsData.queryParams).length > 0">
          <div class="filter-label">当前过滤条件：</div>
          <div class="filter-tags">
            <el-tag v-if="analyticsData.queryParams.merchant_id" type="primary" size="small">
              商户：{{ getMerchantName(analyticsData.queryParams.merchant_id) }}
            </el-tag>
            <el-tag v-if="analyticsData.queryParams.template_id" type="info" size="small">
              模板：{{ getTemplateName(analyticsData.queryParams.template_id) }}
            </el-tag>
            <el-tag v-if="analyticsData.queryParams.start_date && analyticsData.queryParams.end_date" type="success" size="small">
              时间：{{ analyticsData.queryParams.start_date }} 至 {{ analyticsData.queryParams.end_date }}
            </el-tag>
          </div>
        </div>

        <!-- 总体统计 -->
        <div class="summary-stats">
          <el-row :gutter="16">
            <el-col :span="4">
              <div class="summary-card">
                <div class="card-header">
                  <i class="el-icon-s-data"></i>
                  总裂变数
                  <el-tooltip effect="dark" content="扫码核销产生裂变" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </div>
                <div class="card-value">{{ formatNumber(analyticsData.total_fission) }}</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="summary-card">
                <div class="card-header">
                  <i class="el-icon-s-flag"></i>
                  活跃裂变
                  <el-tooltip effect="dark" content="有效裂变数量，一般和总裂变数相等" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </div>
                <div class="card-value">{{ formatNumber(analyticsData.active_fission) }}</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="summary-card">
                <div class="card-header">
                  <i class="el-icon-user-solid"></i>
                  总邀请数
                  <el-tooltip effect="dark" content="活动转发后，对方点击领取领奖码，但未兑换" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </div>
                <div class="card-value">{{ formatNumber(analyticsData.total_invites) }}</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="summary-card">
                <div class="card-header">
                  <i class="el-icon-shopping-cart-2"></i>
                  总领取数
                  <el-tooltip effect="dark" content="活动转发后，对方点击领取领奖码，并成功兑换" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </div>
                <div class="card-value">{{ formatNumber(analyticsData.total_claims) }}</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="summary-card">
                <div class="card-header">
                  <i class="el-icon-trophy"></i>
                  转换率
                  <el-tooltip effect="dark" content="计算公式：总领取数 ÷ 总邀请数 × 100%，反映裂变邀请的实际转化效果" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </div>
                <div class="card-value">{{ formatNumber(analyticsData.conversion_rate) }}%</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="summary-card">
                <div class="card-header">
                  <i class="el-icon-s-marketing"></i>
                  平均邀请数
                  <el-tooltip effect="dark" content="计算公式：总邀请数 ÷ 总裂变数，反映每个裂变活动平均产生的邀请数量" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </div>
                <div class="card-value">{{ formatNumber(analyticsData.avg_invites_per_fission) }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 图表区域 -->
        <div class="charts-section" style="margin-top: 30px;">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="chart-container">
                <h4>每日趋势</h4>
                <div id="dailyTrendChart" style="height: 300px;"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-container">
                <h4>转化率分布</h4>
                <div id="conversionChart" style="height: 300px;"></div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>

    <!-- 配置管理弹窗 -->
    <el-dialog :title="getConfigDialogTitle()" :visible.sync="configDialogVisible" width="700px">
      <el-form :model="configForm" :rules="configRules" ref="configForm" label-width="150px">
        <el-form-item label="最大邀请数" prop="max_invite_count">
          <el-input-number v-model="configForm.max_invite_count" :min="1" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="有效期(天)" prop="expire_days">
          <el-input-number v-model="configForm.expire_days" :min="1" :max="30"></el-input-number>
        </el-form-item>
        <el-form-item label="IP限制(每小时)" prop="ip_limit_per_hour">
          <el-input-number v-model="configForm.ip_limit_per_hour" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="用户每日奖励限制" prop="user_daily_reward_limit">
          <el-input-number v-model="configForm.user_daily_reward_limit" :min="1" :max="20"></el-input-number>
        </el-form-item>
        <el-form-item label="分享标题模板" prop="share_title_template">
          <el-input v-model="configForm.share_title_template" type="textarea" :rows="2" placeholder="支持变量：{merchant_name}"></el-input>
        </el-form-item>
        <el-form-item label="分享描述模板" prop="share_desc_template">
          <el-input v-model="configForm.share_desc_template" type="textarea" :rows="2" placeholder="支持变量：{coupon_name}, {coupon_desc}"></el-input>
        </el-form-item>
        <el-form-item label="分享图片" prop="share_image_url">
          <div style="display: flex; align-items: flex-start; gap: 15px;">
            <!-- 当前图片预览 -->
            <div class="image-preview" style="flex-shrink: 0;">
              <img 
                v-if="configForm.share_image_url" 
                :src="configForm.share_image_url" 
                style="width: 120px; height: 120px; object-fit: cover; border-radius: 6px; border: 1px solid #dcdfe6;"
                @error="handleImageError"
                alt="分享图片预览"
              >
              <div 
                v-else 
                style="width: 120px; height: 120px; background: #f5f7fa; border: 1px dashed #dcdfe6; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: #909399;"
              >
                <i class="el-icon-picture" style="font-size: 24px;"></i>
              </div>
            </div>
            <!-- 上传控件 -->
            <div style="flex: 1;">
              <el-upload
                ref="imageUpload"
                action="#"
                :http-request="handleImageUpload"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                accept="image/*"
                style="width: 100%;">
                <el-button size="small" type="primary" icon="el-icon-upload2" :loading="imageUploading">
                  {{ imageUploading ? '上传中...' : '选择图片' }}
                </el-button>
              </el-upload>
              <div style="margin-top: 8px; color: #909399; font-size: 12px;">
                支持 JPG、PNG 格式，建议尺寸 400x400px，大小不超过 2MB
              </div>
              <div v-if="configForm.share_image_url" style="margin-top: 8px;">
                <el-button size="mini" type="danger" @click="removeImage">移除图片</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="启用状态" prop="is_enabled">
          <el-switch v-model="configForm.is_enabled" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="configDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveConfig" :loading="configSaving">保存配置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UniversalTable from "@/components/TableComponent.vue";
import nfcFissionApi from "@/api/nfc-fission.js";

export default {
  name: 'NfcFissionManagement',
  components: {
    UniversalTable
  },
  data() {
    return {
      detailDialogVisible: false,
      inviteDialogVisible: false,
      analyticsDialogVisible: false,
      analyticsLoading: false,
      configDialogVisible: false,
      configSaving: false,
      imageUploading: false,
      currentFission: null,
      shareLink: '',
      inviteList: [],
      invitePage: 1,
      invitePageSize: 10,
      inviteTotal: 0,
      analyticsData: {},
      templateOptions: [],
      dailyTrendChart: null,
      conversionChart: null,
      columns: [
        {
          prop: "id",
          label: "裂变ID",
          width: "100"
        },
        {
          prop: "merchant_name",
          label: "商户名称",
          width: "150",
          formatter: (row) => {
            return row.merchant?.merchant_name || `商户${row.merchant_id}` || '-'
          }
        },
        {
          prop: "user_openid",
          label: "发起用户OpenID",
          width: "180",
          showOverflowTooltip: true
        },
        {
          prop: "template_id",
          label: "模板ID",
          width: "100"
        },
        {
          prop: "share_code",
          label: "分享码",
          width: "150",
          showOverflowTooltip: true
        },
        {
          prop: "current_invite_count",
          label: "当前邀请数",
          width: "120",
          render: (h, { row }) => {
            return h('span', `${row.current_invite_count}/${row.max_invite_count}`)
          }
        },
        {
          prop: "reward_amount",
          label: "奖励金额",
          width: "100",
          render: (h, { row }) => {
            return h('span', `¥${row.reward_amount}`)
          }
        },
        {
          prop: "status",
          label: "状态",
          width: "100",
          tag: true,
          tagConfig: {
            1: { type: 'success', text: '有效' },
            0: { type: 'danger', text: '失效' }
          }
        },
        {
          prop: "expire_time",
          label: "过期时间",
          width: "180",
          render: (h, { row }) => {
            const now = new Date()
            const expireTime = new Date(row.expire_time)
            const isExpired = expireTime < now
            return h('span', {
              style: { color: isExpired ? '#f56c6c' : '#606266' }
            }, row.expire_time)
          }
        },
        {
          prop: "create_time",
          label: "创建时间",
          width: "180"
        }
      ],
      statusOptions: [
        { value: 1, label: '有效' },
        { value: 0, label: '失效' }
      ],
      merchantOptions: [],
      searchForm: {},
      configForm: {
        max_invite_count: 10,
        expire_days: 7,
        ip_limit_per_hour: 3,
        user_daily_reward_limit: 10,
        share_title_template: '我在【{merchant_name}】获得了优惠券，邀请你一起领取！',
        share_desc_template: '{coupon_name}，{coupon_desc}，限时领取！',
        share_image_url: '',
        is_enabled: 1
      },
      configRules: {
        max_invite_count: [
          { required: true, message: '请设置最大邀请数', trigger: 'blur' },
          { type: 'number', min: 1, max: 100, message: '最大邀请数必须在1-100之间', trigger: 'blur' }
        ],
        expire_days: [
          { required: true, message: '请设置有效期', trigger: 'blur' },
          { type: 'number', min: 1, max: 30, message: '有效期必须在1-30天之间', trigger: 'blur' }
        ],
        ip_limit_per_hour: [
          { required: true, message: '请设置IP限制', trigger: 'blur' },
          { type: 'number', min: 1, max: 10, message: 'IP每小时限制必须在1-10之间', trigger: 'blur' }
        ],
        user_daily_reward_limit: [
          { required: true, message: '请设置用户每日奖励限制', trigger: 'blur' },
          { type: 'number', min: 1, max: 20, message: '用户每日奖励限制必须在1-20之间', trigger: 'blur' }
        ],
        share_title_template: [
          { required: true, message: '请设置分享标题模板', trigger: 'blur' },
          { min: 1, max: 200, message: '分享标题模板长度必须在1-200个字符之间', trigger: 'blur' }
        ],
        share_desc_template: [
          { required: true, message: '请设置分享描述模板', trigger: 'blur' },
          { min: 1, max: 300, message: '分享描述模板长度必须在1-300个字符之间', trigger: 'blur' }
        ],
        share_image_url: [
          { required: false, message: '分享图片不是必填项', trigger: 'blur' }
        ]
      }
    };
  },
  async mounted() {
    await this.loadTemplateOptions();
    await this.loadMerchantOptions();
    await this.loadConfig();
  },
  beforeDestroy() {
    // 清理图表实例
    if (this.dailyTrendChart) {
      this.dailyTrendChart.dispose();
    }
    if (this.conversionChart) {
      this.conversionChart.dispose();
    }
  },
  methods: {
    // 获取表格数据
    async fetchTableData(params = {}) {
      const postData = Object.assign({}, params, this.searchForm);
      try {
        const result = await nfcFissionApi.getList(postData);
        return {
          list: result.data.list,
          total: result.data.total
        };
      } catch (e) {
        this.$message.error(e.message);
        throw e;
      }
    },

    // 加载模板选项
    async loadTemplateOptions() {
      try {
        const result = await nfcFissionApi.getTemplates();
        if (result.code === 200) {
          this.templateOptions = result.data;
        }
      } catch (e) {
        console.error('加载模板失败:', e);
      }
    },

    // 加载商户选项
    async loadMerchantOptions() {
      try {
        const result = await nfcFissionApi.getMerchants();
        if (result.code === 200) {
          this.merchantOptions = result.data.map(item => ({
            id: item.id,
            name: item.merchant_name || item.name || `商户${item.id}`
          }));
        }
      } catch (e) {
        console.error('加载商户失败:', e);
        // 使用临时模拟数据作为备选
        this.merchantOptions = [
          { id: 1, name: '测试商户1' },
          { id: 5, name: '测试商户5' }
        ];
      }
    },

    // 重置搜索
    reset() {
      this.searchForm = {};
    },

    // 处理日期范围变化
    handleDateRangeChange(dates) {
      if (dates && dates.length === 2) {
        this.searchForm.start_date = dates[0];
        this.searchForm.end_date = dates[1];
      } else {
        delete this.searchForm.start_date;
        delete this.searchForm.end_date;
      }
    },

    // 处理过期日期范围变化
    handleExpireDateRangeChange(dates) {
      if (dates && dates.length === 2) {
        this.searchForm.expire_start_date = dates[0];
        this.searchForm.expire_end_date = dates[1];
      } else {
        delete this.searchForm.expire_start_date;
        delete this.searchForm.expire_end_date;
      }
    },

    // 查看详情
    async handleView(row) {
      this.currentFission = row;
      this.shareLink = `${process.env.VUE_APP_API_BASE_URL}/nfc-fission-share.html?share_code=${row.share_code}`;
      this.detailDialogVisible = true;
    },

    // 查看邀请记录
    async handleViewInvites(row) {
      try {
        const result = await nfcFissionApi.getInvites(row.id, {
          page: this.invitePage,
          limit: this.invitePageSize
        });
        if (result.code === 200) {
          this.inviteList = result.data.list;
          this.inviteTotal = result.data.total;
          this.inviteDialogVisible = true;
        }
      } catch (e) {
        this.$message.error('获取邀请记录失败');
      }
    },

    // 邀请记录分页
    handleInviteSizeChange(val) {
      this.invitePageSize = val;
      this.handleViewInvites(this.currentFission);
    },

    handleInviteCurrentChange(val) {
      this.invitePage = val;
      this.handleViewInvites(this.currentFission);
    },

    // 复制分享链接
    handleCopyShareLink(row) {
      const shareLink = `${process.env.VUE_APP_API_BASE_URL}/nfc-fission-share.html?share_code=${row.share_code}`;
      this.copyToClipboard(shareLink);
    },

    // 复制分享链接（详情弹窗）
    copyShareLink() {
      this.copyToClipboard(this.shareLink);
    },

    // 复制到剪贴板
    copyToClipboard(text) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success('链接已复制到剪贴板');
        }).catch(() => {
          this.fallbackCopyTextToClipboard(text);
        });
      } else {
        this.fallbackCopyTextToClipboard(text);
      }
    },

    // 备用复制方法
    fallbackCopyTextToClipboard(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        document.execCommand('copy');
        this.$message.success('链接已复制到剪贴板');
      } catch (err) {
        this.$message.error('复制失败，请手动复制');
      }
      document.body.removeChild(textArea);
    },

    // 禁用裂变
    async handleDisable(row) {
      this.$confirm('确认要禁用这个裂变吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const result = await nfcFissionApi.disable(row.id);
          if (result.code === 200) {
            this.$message.success('禁用成功');
            this.$refs.table.refresh();
          } else {
            this.$message.error(result.message || '禁用失败');
          }
        } catch (e) {
          this.$message.error(e.message);
        }
      });
    },

    // 删除裂变
    async handleDelete(row) {
      this.$confirm('确认要删除这个裂变记录吗？删除后无法恢复！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const result = await nfcFissionApi.delete(row.id);
          if (result.code === 200) {
            this.$message.success('删除成功');
            this.$refs.table.refresh();
          } else {
            this.$message.error(result.message || '删除失败');
          }
        } catch (e) {
          this.$message.error(e.message);
        }
      });
    },

    // 数据分析
    async handleAnalytics() {
      this.analyticsLoading = true;
      try {
        // 构建查询参数
        const queryParams = {};

        // 传递商户ID过滤
        if (this.searchForm.merchant_id) {
          queryParams.merchant_id = this.searchForm.merchant_id;
        }

        // 传递其他可能的过滤条件
        if (this.searchForm.start_date) {
          queryParams.start_date = this.searchForm.start_date;
        }
        if (this.searchForm.end_date) {
          queryParams.end_date = this.searchForm.end_date;
        }
        if (this.searchForm.template_id) {
          queryParams.template_id = this.searchForm.template_id;
        }

        const result = await nfcFissionApi.getAnalytics(queryParams);
        if (result.code === 200) {
          // 正确映射数据结构
          this.analyticsData = {
            // 将stats中的数据提取到顶级属性
            total_fission: result.data.stats?.total_fission || 0,
            active_fission: result.data.stats?.active_fission || 0,
            total_invites: result.data.stats?.total_invites || 0,
            total_claims: result.data.stats?.total_claims || 0,
            conversion_rate: result.data.stats?.conversion_rate || 0,
            avg_invites_per_fission: result.data.stats?.avg_invites_per_fission || 0,
            // 保持原有的趋势和排行数据
            trend: result.data.trend || [],
            ranking: result.data.ranking || [],
            // 保存查询参数用于显示
            queryParams: queryParams
          };
          this.analyticsDialogVisible = true;
          this.$nextTick(() => {
            this.renderCharts();
          });
        } else {
          this.$message.error(result.message || '获取分析数据失败');
        }
      } catch (e) {
        this.$message.error('获取分析数据失败：' + (e.message || '网络错误'));
      } finally {
        this.analyticsLoading = false;
      }
    },

    // 渲染图表
    renderCharts() {
      // 使用 ECharts 渲染图表
      this.renderDailyTrendChart();
      this.renderConversionChart();
    },

    // 渲染每日趋势图表
    renderDailyTrendChart() {
      const echarts = require('echarts');
      const chartDom = document.getElementById('dailyTrendChart');

      if (!chartDom) return;

      // 销毁已存在的图表实例
      if (this.dailyTrendChart) {
        this.dailyTrendChart.dispose();
      }

      this.dailyTrendChart = echarts.init(chartDom);

      // 处理趋势数据
      const trendData = this.analyticsData.trend || [];

      // 检查是否有数据
      if (trendData.length === 0) {
        const option = {
          title: {
            text: '每日裂变趋势',
            left: 'center',
            textStyle: {
              fontSize: 16,
              fontWeight: 'normal'
            }
          },
          graphic: {
            elements: [
              {
                type: 'text',
                left: 'center',
                top: 'middle',
                style: {
                  text: '暂无数据',
                  fontSize: 16,
                  fill: '#999'
                }
              }
            ]
          }
        };
        this.dailyTrendChart.setOption(option);
        return;
      }

      const dates = trendData.map(item => item.date);
      const fissionCounts = trendData.map(item => item.fission_count);
      const inviteCounts = trendData.map(item => parseInt(item.invite_count));

      const option = {
        title: {
          text: '每日裂变趋势',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['裂变数量', '邀请数量'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '裂变数量',
            type: 'line',
            stack: 'Total',
            data: fissionCounts,
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '邀请数量',
            type: 'line',
            stack: 'Total',
            data: inviteCounts,
            smooth: true,
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      };

      this.dailyTrendChart.setOption(option);
    },

    // 渲染转化率分布图表
    renderConversionChart() {
      const echarts = require('echarts');
      const chartDom = document.getElementById('conversionChart');

      if (!chartDom) return;

      // 销毁已存在的图表实例
      if (this.conversionChart) {
        this.conversionChart.dispose();
      }

      this.conversionChart = echarts.init(chartDom);

      // 处理商户排行数据
      const rankingData = this.analyticsData.ranking || [];

      // 检查是否有数据
      if (rankingData.length === 0) {
        const option = {
          title: {
            text: '商户转化率分布',
            left: 'center',
            textStyle: {
              fontSize: 16,
              fontWeight: 'normal'
            }
          },
          graphic: {
            elements: [
              {
                type: 'text',
                left: 'center',
                top: 'middle',
                style: {
                  text: '暂无数据',
                  fontSize: 16,
                  fill: '#999'
                }
              }
            ]
          }
        };
        this.conversionChart.setOption(option);
        return;
      }

      const merchantNames = rankingData.map(item => item.merchant_name);
      const conversionRates = rankingData.map(item => item.conversion_rate);

      const option = {
        title: {
          text: '商户转化率分布',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: merchantNames,
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '转化率(%)'
        },
        series: [
          {
            name: '转化率',
            type: 'bar',
            data: conversionRates,
            itemStyle: {
              color: '#E6A23C'
            }
          }
        ]
      };

      this.conversionChart.setOption(option);
    },

    // 数字格式化
    formatNumber(value) {
      if (value === null || value === undefined) {
        return '-';
      }

      const num = Number(value);
      if (isNaN(num)) {
        return '-';
      }

      // 如果是小数，保留两位小数
      if (num % 1 !== 0) {
        return num.toFixed(2);
      }

      // 整数直接返回
      return num.toString();
    },

    // 获取数据分析弹窗标题
    getAnalyticsTitle() {
      if (this.analyticsData.queryParams && this.analyticsData.queryParams.merchant_id) {
        const merchantName = this.getMerchantName(this.analyticsData.queryParams.merchant_id);
        return `裂变数据分析 - ${merchantName}`;
      }
      return '裂变数据分析 - 全部数据';
    },

    // 获取商户名称
    getMerchantName(merchantId) {
      const merchant = this.merchantOptions.find(item => item.id === merchantId);
      return merchant ? merchant.name : `商户${merchantId}`;
    },

    // 获取模板名称
    getTemplateName(templateId) {
      const template = this.templateOptions.find(item => item.id === templateId);
      return template ? template.name : `模板${templateId}`;
    },

    // 配置管理
    async handleConfig() {
      // 检查是否选择了商户
      if (!this.searchForm.merchant_id) {
        this.$message.warning('请先选择商户再进行配置管理');
        return;
      }

      // 加载选中商户的配置
      await this.loadConfig();
      this.configDialogVisible = true;
    },

    // 加载配置
    async loadConfig() {
      try {
        const params = {
          merchant_id: this.searchForm.merchant_id
        };
        const result = await nfcFissionApi.getConfig(params);
        if (result.code === 200) {
          this.configForm = { ...this.configForm, ...result.data };
        } else {
          // 显示具体的错误信息
          let errorMessage = result.message || '加载配置失败';
          if (result.data && result.data.errors) {
            errorMessage = result.data.errors;
          }
          this.$message.error(errorMessage);
        }
      } catch (e) {
        console.error('加载配置失败:', e);
        this.$message.error('加载配置失败：' + (e.message || '网络错误'));
      }
    },

    // 保存配置
    async handleSaveConfig() {
      this.$refs.configForm.validate(async (valid) => {
        if (valid) {
          this.configSaving = true;
          try {
            // 确保包含merchant_id
            const configData = {
              ...this.configForm,
              merchant_id: this.searchForm.merchant_id
            };
            const result = await nfcFissionApi.saveConfig(configData);
            if (result.code === 200) {
              this.$message.success('配置保存成功');
              this.configDialogVisible = false;
            } else {
              // 显示具体的验证错误信息
              let errorMessage = result.message || '保存失败';
              if (result.data && result.data.errors) {
                errorMessage = result.data.errors;
              }
              this.$message.error(errorMessage);
            }
          } catch (e) {
            this.$message.error(e.message);
          } finally {
            this.configSaving = false;
          }
        }
      });
    },

    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        'active': 'success',
        'completed': 'primary',
        'disabled': 'danger',
        'expired': 'info'
      };
      return typeMap[status] || 'info';
    },

    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        'active': '活跃',
        'completed': '已完成',
        'disabled': '已禁用',
        'expired': '已过期'
      };
      return textMap[status] || '未知';
    },

    // 获取转化率
    getConversionRate() {
      if (!this.currentFission || !this.currentFission.invite_count) {
        return 0;
      }
      return Math.round((this.currentFission.success_count / this.currentFission.invite_count) * 100);
    },

    // 获取配置弹窗标题
    getConfigDialogTitle() {
      if (this.searchForm.merchant_id) {
        const merchantName = this.getMerchantName(this.searchForm.merchant_id);
        return `裂变配置管理 - ${merchantName}`;
      }
      return '裂变配置管理';
    },

    // 图片上传前校验
    beforeImageUpload(file) {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGOrPNG) {
        this.$message.error('只能上传 JPG 或 PNG 格式的图片！');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB！');
        return false;
      }
      return true;
    },

    // 处理图片上传
    async handleImageUpload(options) {
      this.imageUploading = true;
      try {
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', options.file);

        // 使用现有的上传接口
        const response = await this.$http({
          url: '/upload/uploadImage',
          method: 'POST',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        if (response.data.code === 0) {
          this.configForm.share_image_url = response.data.data;
          this.$message.success('图片上传成功');
          // 通知上传组件成功
          options.onSuccess(response.data);
        } else {
          this.$message.error(response.data.msg || response.data.message || '上传失败');
          options.onError(new Error(response.data.msg || response.data.message || '上传失败'));
        }
      } catch (error) {
        console.error('上传失败:', error);
        this.$message.error('上传失败：' + (error.message || '网络错误'));
        options.onError(error);
      } finally {
        this.imageUploading = false;
      }
    },

    // 移除图片
    removeImage() {
      this.$confirm('确认移除当前分享图片？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.configForm.share_image_url = '';
        this.$message.success('图片已移除');
      }).catch(() => {
        // 用户取消操作
      });
    },

    // 处理图片加载错误
    handleImageError() {
      this.$message.error('图片加载失败');
      // 可以选择清空图片URL或显示默认图片
      // this.configForm.share_image_url = '';
    }
  }
};
</script>

<style scoped>
.page-box {
  padding: 20px;
}


.fission-detail {
  margin-bottom: 20px;
}

.share-link-section h4,
.invite-stats h4 {
  margin-bottom: 15px;
  color: #333;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.summary-stats {
  margin-bottom: 30px;
}

.summary-card {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  text-align: center;
}

.card-header {
  font-size: 13px;
  color: #666;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  white-space: nowrap;
  flex-wrap: nowrap;
  min-height: 20px;
}

.card-header i {
  font-size: 16px;
  color: #409eff;
}

.card-header .el-icon-question {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
  cursor: help;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
}

.chart-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.chart-container h4 {
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.analytics-content {
  max-height: 70vh;
  overflow-y: auto;
}

.filter-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.filter-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-tags .el-tag {
  margin-right: 0;
}

</style>
